package com.jzo2o.foundations.xxljob;

import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.service.IHomeService;
import com.jzo2o.foundations.service.IRegionService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * springCache缓存同步任务
 *
 * @author itcast
 * @create 2023/8/15 18:14
 **/
@Slf4j
@Component
public class SpringCacheSyncHandler {

    @Resource
    private IRegionService regionService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private IHomeService homeService;

    /**
     * 已启用区域缓存更新
     * 每日凌晨1点执行
     */
    @XxlJob(value = "activeRegionCacheSync")
    public void activeRegionCacheSync() {
        log.info(">>>>>>>>开始进行缓存同步，更新已启用区域");
        //1.清理缓存
        String key = RedisConstants.CacheName.JZ_CACHE + "::ACTIVE_REGIONS";
        redisTemplate.delete(key);

        //2.调用打了SpringCache注解的service方法, 刷新缓存
        List<RegionSimpleResDTO> regionList = regionService.queryActiveRegionListCache();
        log.info(">>>>>>>>更新已启用区域完成");

        //更新首页服务列表
        regionList.forEach(item->{
            //清空首页服务缓存
            Long regionId = item.getId();
            String serveIconCacheKey = RedisConstants.CacheName.SERVE_ICON + "::" + regionId;
            redisTemplate.delete(serveIconCacheKey);
            //查询首页服务数据
            homeService.getFirstPageServeList(regionId);
        });


    }

}